package net.alteiar.algorithms.builder;

import java.awt.Color;
import java.awt.image.BufferedImage;

import net.alteiar.Array2D;
import net.alteiar.images.BasicImage;
import net.alteiar.images.metadata.ImageInfo;
import weka.core.Instance;

public class ImageRGBBuilder implements InstanceBuilder {

	private static double[] elementValue(BasicImage img, int x, int y,
			int squareSize) {
		BufferedImage im = img.getImage();
		Array2D rgbEach = new Array2D(3 * squareSize, squareSize);

		int realX = x * squareSize;
		int realY = y * squareSize;
		for (int k = 0; k < squareSize; ++k) {
			for (int k1 = 0; k1 < squareSize; ++k1) {
				Color c = new Color(im.getRGB(realX + k, realY + k1));
				rgbEach.set(k * 3, k1, c.getRed());
				rgbEach.set(k * 3 + 1, k1, c.getGreen());
				rgbEach.set(k * 3 + 2, k1, c.getBlue());
			}
		}

		int[] val = rgbEach.getArray();

		double[] result = new double[3 * squareSize * squareSize];
		for (int k = 0; k < val.length; ++k) {
			result[k] = val[k];
		}

		return result;
	}

	private final int squareSize;

	public ImageRGBBuilder() {
		squareSize = 2;
	}

	@Override
	public Instance createInstance(ImageInfo info, int x, int y) {
		return new Instance(1.0,
				elementValue(info.getImage(), x, y, squareSize));
	}

	@Override
	public String[] getAttributs() {
		String[] attributs = new String[squareSize * squareSize * 3];
		for (int i = 0; i < attributs.length; i++) {
			attributs[i] = " " + i;
		}
		return attributs;
	}
}
